package com.think.cloud.thinkshop.mall.service.order.impl;


import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.think.cloud.thinkshop.mall.controller.app.order.vo.AppOrderCartRespVO;
import com.think.cloud.thinkshop.mall.controller.app.order.vo.AppOrderDetailPageRespVO;
import com.think.cloud.thinkshop.mall.convert.order.OrderConvert;
import com.think.cloud.thinkshop.mall.domain.order.OrderDetail;
import com.think.cloud.thinkshop.mall.mapper.order.OrderDetailMapper;
import com.think.cloud.thinkshop.mall.service.order.AppOrderDetailService;
import com.think.common.core.exception.util.ServiceExceptionUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

import static com.think.common.core.exception.enums.ErrorCode.ORDER_CANNOT_CANCEL_ERROR;
import static com.think.common.core.exception.enums.ErrorCode.ORDER_DETAIL_NOT_EXIST_ERROR;

/**
 * 订单明细AppService业务层处理
 *
 * @author zkthink
 * @date 2024-05-27
 */
@Service
public class AppOrderDetailServiceImpl implements AppOrderDetailService {
    @Autowired
    private OrderDetailMapper orderDetailMapper;

    @Async
    @Override
    public void batchInsert(List<AppOrderCartRespVO> carts, Long orderId) {
        List<OrderDetail> details = new ArrayList<>();
        for (AppOrderCartRespVO cart : carts) {
            for (int i = 0; i < cart.getNum(); i++) {
                OrderDetail orderDetail = OrderConvert.INSTANCE.convert(cart);
                orderDetail.setOrderId(orderId);
                details.add(orderDetail);
            }
        }
        orderDetailMapper.batchInsert(details);
    }

    @Override
    public List<AppOrderDetailPageRespVO> getOrderDetail(List<Long> orderIds) {
        return orderDetailMapper.getOrderDetail(orderIds);
    }

    @Override
    public List<OrderDetail> getOrderDetailByOrderId(Long orderId) {
        List<OrderDetail> orderDetails =
                orderDetailMapper.selectList(new LambdaQueryWrapper<OrderDetail>().eq(OrderDetail::getOrderId, orderId));
        if(CollectionUtils.isEmpty(orderDetails))
            ServiceExceptionUtil.exception(ORDER_DETAIL_NOT_EXIST_ERROR);
        return orderDetails;
    }
}
